package com.yj.suncity.activity.shouye;

import java.util.List;

import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.activity.shouye.bean.SuperadvListBean;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.ThreadUtils;
import com.yj.suncity.async.ThreadUtils.OnResultListener;
import com.yj.suncity.bean.AdvBean;
import com.yj.suncity.bean.AdvListBean;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.utis.PullToRefreshView;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.Utils;
import com.yj.suncity.utis.PullToRefreshView.OnFooterRefreshListener;
import com.yj.suncity.utis.PullToRefreshView.OnHeaderRefreshListener;
import com.yj.suncity.viewpager.ViewPagerScrollSuperadv;
import com.yj.suncity.viewpager.ViewPagerScrollSuperadv.OnPagerClick;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SeeAdvListActivity extends Activity implements OnClickListener,
		OnFooterRefreshListener, OnHeaderRefreshListener {

	private Context context;
	private int currIndex = 0;// 当前编号
	private int zero = 0;// 动画图片偏移量
	private int one;// 单个水平动画位移
	private int two;
	private int three;
	private int mWidth;
	private View mView_mark;
	// private ProgressBar progressBar;
	private String cityId;
	private String userId;
	private String titleName;
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();

	private boolean mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
	private boolean mRefreshFlag = false;// 判断是否刷新
	private PullToRefreshView mPullToRefreshView = null;
	private int pageNum = 1;
	private String type = "";// (排序值:sj(按发布时间排序降序)、je(按金额降序排序)、rq(按人气降序排序))
	private ListView mList_see_adv;
	private SeeAdvAdapter adapter;
	private List<AdvBean> detailInfos;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	private String tradeId;// 行业Id
	private ViewPager pager;
	private LinearLayout lay_view_select;
	private ViewPagerScrollSuperadv scrollSuperadv;
	private int flag;// 1、首页->当前;2、分类信息->当前

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_see_adv);
		context = this;
		mWidth = getResources().getDisplayMetrics().widthPixels;
		one = mWidth / 4;// 设置水平动画平移大小
		two = 2 * one;
		three = 3 * one;
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				//.displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		cityId = preferencesUtil.getString(context, ShareCon.CITYFILE,
				ShareCon.CITYID, "140881");
		userId = getIntent().getStringExtra("userid");
		titleName = getIntent().getStringExtra("titlename");
		tradeId = getIntent().getStringExtra("tradeid");
		flag = getIntent().getIntExtra("flag", -1);
		if (userId == null) {
			userId = "";
		}
		if (titleName == null) {
			titleName = "看广告";
		}
		if (tradeId == null) {
			tradeId = "";
		}
		findView();
		initData(1, "");
		
		if (flag==1) {// 从首页跳转过来得加超广告请求数据
			getAdv();// 超管广告
		}

	}

	private void findView() {
		((TextView) findViewById(R.id.txt_title_name)).setText(titleName);
		findViewById(R.id.btnHeadBack).setOnClickListener(this);
		findViewById(R.id.txt_btn_all).setOnClickListener(this);
		findViewById(R.id.txt_btn_time).setOnClickListener(this);
		findViewById(R.id.txt_btn_price).setOnClickListener(this);
		findViewById(R.id.txt_btn_moods).setOnClickListener(this);

		mView_mark = findViewById(R.id.lay_rela_mark);
		mView_mark.setLayoutParams(new RelativeLayout.LayoutParams(one, Utils
				.dipTopx(context, 3)));

		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		TextView emptyView = (TextView) findViewById(R.id.txt_empty);
		mList_see_adv = (ListView) findViewById(R.id.list_see_adv);
		mList_see_adv.setEmptyView(emptyView);
		if (flag == 1) {// 从首页跳转过来得加超广告
		View view = LayoutInflater.from(context).inflate(R.layout.view_page,
				null);
		lay_view_select = (LinearLayout) view
				.findViewById(R.id.lay_view_select);
		RelativeLayout layout = (RelativeLayout) view
				.findViewById(R.id.lay_view_page);
		layout.setLayoutParams(new LinearLayout.LayoutParams(mWidth,
				(int) (mWidth / 3)));
		pager = (ViewPager) view.findViewById(R.id.view_pager);
		mList_see_adv.addHeaderView(view);
		}
	}

	private void initData(int i, String order) {

		String path = URLCon.广告 + "?action=seeadvlist&pagesize=20&pageindex="
				+ i + "&order=" + order + "&cityid=" + cityId + "&tradeid="
				+ tradeId + "&userid=" + userId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null,
				mPullToRefreshView, mRefreshFlag, null, true, "正在加载......",
				new AsyncTaskUtil.ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						AdvListBean listBean = new AdvListBean(jsonObject);
						pageNum = Integer.valueOf(listBean.getTotalpage());
						if (mRefreshHeadFlag) {
							adapter = null;
						}
						if (adapter == null) {
							detailInfos = listBean.getData();
							adapter = new SeeAdvAdapter(detailInfos);
							mList_see_adv.setAdapter(adapter);
						} else {
							detailInfos.addAll(listBean.getData());
							adapter.notifyDataSetChanged();
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void getAdv() {
		String path = URLCon.超广广告 + "?action=superadvlist&cityid=" + cityId
				+ "&type=2";
		Log.d("", "超广广告=" + path);
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				SuperadvListBean listBean = new SuperadvListBean(json);
				scrollSuperadv = new ViewPagerScrollSuperadv(context,
						imageLoader, options, pager, lay_view_select, listBean
								.getData(),new OnPagerClick() {
									@Override
									public void onPagerClick(String advid, String adv_userid) {
										Intent intent = new Intent(context,
												SeeAdvDetailActivity.class);
										intent.putExtra("adv_userid", adv_userid);
										intent.putExtra("advid", advid);
										intent.putExtra("flag", 2);
										startActivity(intent);
										
									}
								});
			}
		});
	}

	@Override
	protected void onResume() {
		if (scrollSuperadv != null) {
			scrollSuperadv.startTimer();
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		if (scrollSuperadv != null) {
			scrollSuperadv.stopTimer();
		}
		super.onPause();
	}

	class SeeAdvAdapter extends BaseAdapter {
		private List<AdvBean> advBeans;

		public SeeAdvAdapter(List<AdvBean> advBeans) {
			super();
			imageLoader = ImageLoader.getInstance();
			this.advBeans = advBeans;
		}

		@Override
		public int getCount() {
			return advBeans.size();
		}

		@Override
		public Object getItem(int position) {
			return advBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.adapter_see_adv_list, null);
				holder.mImg_logo = (ImageView) convertView
						.findViewById(R.id.img_logo);
				holder.mTxt_name = (TextView) convertView
						.findViewById(R.id.txt_shop_name);
				holder.mTxt_jianjie = (TextView) convertView
						.findViewById(R.id.txt_shop_jianjie);
				holder.mTxt_all_totle = (TextView) convertView
						.findViewById(R.id.txt_all_num);
				holder.mTxt_give_num = (TextView) convertView
						.findViewById(R.id.txt_give_num);
				holder.mLay_linear_adv_item = (LinearLayout) convertView
						.findViewById(R.id.lay_linear_adv_item);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final AdvBean advBean = advBeans.get(position);
			holder.mTxt_name.setText(advBean.getEntname());
			holder.mTxt_jianjie.setText(advBean.getEnt_jianjie());
			holder.mTxt_all_totle.setText(advBean.getAmount());
			holder.mTxt_give_num.setText(advBean.getSurplus_num());
			if (!advBean.getEnt_logo().equals("")) {
				imageLoader.displayImage(URLCon.HOST + advBean.getEnt_logo(),
						holder.mImg_logo, options);
			} else {
				holder.mImg_logo
						.setImageResource(R.drawable.android_layout_detail);
			}
			holder.mLay_linear_adv_item
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if (flag==1) {
								Intent intent = new Intent(context,
										SeeAdvLogoActivity.class);
								intent.putExtra("adv_userid", advBean.getUserid());
								intent.putExtra("title", advBean.getAdv_title());
								intent.putExtra("advid", advBean.getAid());
								intent.putExtra("flag", flag);
								intent.putExtra("logo", advBean.getAdv_img());
								startActivity(intent);
							} else {
								Intent intent = new Intent(context, SeeAdvDetailActivity.class);
								intent.putExtra("adv_userid", advBean.getUserid());
								intent.putExtra("advid", advBean.getAid());
								intent.putExtra("flag", flag);
								startActivity(intent);
							}
						}
					});
			return convertView;
		}
	}

	class ViewHolder {
		ImageView mImg_logo;
		TextView mTxt_name;
		TextView mTxt_jianjie;
		TextView mTxt_all_totle;
		TextView mTxt_give_num;
		LinearLayout mLay_linear_adv_item;
	}

	/**
	 * 点击横向按钮恢复状态
	 */
	private void initStatus() {
		mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
		mRefreshFlag = false;// 判断是否刷新
		indexPage = 1;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.txt_btn_all:// 全部
			showView(0);
			break;
		case R.id.txt_btn_time:// 时间
			showView(1);
			break;
		case R.id.txt_btn_price:// 金额
			showView(2);
			break;
		case R.id.txt_btn_moods:// 人气
			showView(3);
			break;
		default:
			break;
		}
	}

	private void showView(int tagStr) {
		if (tagStr == currIndex) {
			return;
		}
		Animation animation = null;
		switch (tagStr) {
		case 0:
			type = "";
			if (currIndex == 1) {
				animation = new TranslateAnimation(one, 0, 0, 0);
			} else if (currIndex == 2) {
				animation = new TranslateAnimation(two, 0, 0, 0);
			} else if (currIndex == 3) {
				animation = new TranslateAnimation(three, 0, 0, 0);
			}
			break;
		case 1:
			type = "sj";
			if (currIndex == 0) {
				animation = new TranslateAnimation(zero, one, 0, 0);
			} else if (currIndex == 2) {
				animation = new TranslateAnimation(two, one, 0, 0);
			} else if (currIndex == 3) {
				animation = new TranslateAnimation(three, one, 0, 0);
			}
			break;
		case 2:
			type = "je";
			if (currIndex == 0) {
				animation = new TranslateAnimation(zero, two, 0, 0);
			} else if (currIndex == 1) {
				animation = new TranslateAnimation(one, two, 0, 0);
			} else if (currIndex == 3) {
				animation = new TranslateAnimation(three, two, 0, 0);
			}
			break;
		case 3:
			type = "rq";
			if (currIndex == 0) {
				animation = new TranslateAnimation(zero, three, 0, 0);
			} else if (currIndex == 1) {
				animation = new TranslateAnimation(one, three, 0, 0);
			} else if (currIndex == 2) {
				animation = new TranslateAnimation(two, three, 0, 0);
			}
			break;
		}
		currIndex = tagStr;
		animation.setFillAfter(true);// True:图片停在动画结束位置
		animation.setDuration(150);
		mView_mark.startAnimation(animation);
		initStatus();
		initData(indexPage, type);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = false;
				mRefreshFlag = true;

				++indexPage;
				if (indexPage > pageNum) {
					ToastUtil.ShowToast(context, "没有更多数据！");
					mPullToRefreshView.onFooterRefreshComplete();
					return;
				} else {
					initData(indexPage, type);
				}

				// mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1);

	}

	int indexPage = 1;

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = true;
				mRefreshFlag = true;
				// if (async != null) {
				// Utils.cancelTaskInterrupt(async);
				// async = null;
				// }
				indexPage = 1;// 刷新头部时将页数初始化为1
				initData(indexPage, type);
				// mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1);
	}

}
